package com.treasure.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

/**
 * 获取服务器IP
 */
public class InetUtils {
    private static final Logger logger = LoggerFactory.getLogger(InetUtils.class);

    public static InetAddress getLocalAddress() {
        try {
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
            while (interfaces.hasMoreElements()) {
                NetworkInterface n = interfaces.nextElement();
                // 该网卡接口下的ip会有多个，也需要一个个的遍历，找到自己所需要的
                Enumeration<InetAddress> addresses = n.getInetAddresses();
                while (addresses.hasMoreElements()) {
                    InetAddress address = addresses.nextElement();
                    // 不是loopback回环类型地址并且是site-local地址
                    if (!address.isLoopbackAddress() && address.isSiteLocalAddress()) {
                        return address;
                    }
                }
            }
        } catch (Exception e) {
            logger.error("获取本地ip地址失败", e);
        }
        return null;
    }

    public static String getLocalIpSuffix() {
        InetAddress localAddress = getLocalAddress();
        if(localAddress != null){
            String hostAddress = localAddress.getHostAddress();
            String[] ipSplit = StringUtils.split(hostAddress, "\\.");
            if(ipSplit.length == 4){
                return ipSplit[2] + "." + ipSplit[3];
            }
        }
        return "";
    }

    public static String getLocalIp() {
        InetAddress localAddress = getLocalAddress();
        if(localAddress != null){
            return localAddress.getHostAddress();
        }
        return "";
    }
}
